package org.sundatagroup.aurora.core.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.sundatagroup.aurora.core.entity.model.ProjectModel;
import org.sundatagroup.aurora.core.entity.pojo.Project;

import java.util.List;

/**
 * <p>{@link Project} 类的相关 DAO 操作, 使用的是 {@link ProjectModel} 类
 * </p>
 * 
 * @author Zdream
 * @date 2018-04-03
 * @since 0.1
 */
@Repository
public class ProjectDao {
    @Autowired
    MongoTemplate mongoOps;

    private final static Logger LOGGER = LoggerFactory.getLogger(ProjectDao.class);
    /**
     * 添加操作
     * @param p
     */
    public void insert(ProjectModel p) {
    	mongoOps.insert(p);
    }

    /**
     * 查操作
     */
    public ProjectModel findByPid(int pid) {
        ProjectModel pm;
        Query query = Query.query(Criteria.where("pid").is(pid));
        if ((pm = mongoOps.findOne(query, ProjectModel.class)) == null) {
            LOGGER.error("根据pid查询项目失败，请检查!");
            return null;
        } else {
            return pm;
        }
    }
    
    /**
     * 返回所有的 {@link Project}
     * @return
     */
    public List<ProjectModel> findAll() {
        List<ProjectModel> pms;
        if ((pms = mongoOps.findAll(ProjectModel.class)) == null) {
            LOGGER.error("查找所有Project结果为null，请检查!");
            return null;
        } else {
            return pms;
        }
    }

    /**
     * 用分页的方式进行{@link ProjectModel}的查询
     * @param start 起始索引
     * @param size 数据条目数量
     * @return
     */
    public List<ProjectModel> findByPage(int start, int size) {
        List<ProjectModel> pms;
        Query query = new Query()
                .with(new Sort(new Sort.Order(Sort.Direction.ASC, "pid")))
                .skip(start)
                .limit(size);
        if ((pms = mongoOps.find(query, ProjectModel.class)) == null) {
            LOGGER.error("分页查询Project结果为null，请检查！");
            return null;
        } else {
            return pms;
        }
    }

    /**
     * 返回 {@link Project} 数量
     * @return
     */
    public int count() {
       return (int) mongoOps.count(new Query(), ProjectModel.class);
    }
}
